package deng.jbe.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

import deng.jbe.ejb.MyStatelessRemote;

public class InvokeRemoteEjb {
	public static void main(String[] args) {
		new InvokeRemoteEjb().run();
	}
	
	private static Logger logger = Logger.getLogger(InvokeRemoteEjb.class);

	public void run() {

		Properties props = new Properties();
		props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		props.setProperty(Context.PROVIDER_URL, "localhost:1099");
		
		try {
			logger.info("Looking up EJB");
			Context ctx = new InitialContext(props);
			logger.info(ctx);
			Object bean = ctx.lookup("jbe-ear/MyStatelessBean/remote");
			logger.info("EJB remote bean " + bean);
			final MyStatelessRemote myBean = (MyStatelessRemote)bean;
			List<Thread> threads = new ArrayList<Thread>();
			for (int i = 0; i < 50; i ++) {
				logger.info("Invoking thread#" + i);
				threads.add(new Thread(new Runnable() {

					@Override
					public void run() {
						myBean.runIt();
					}
					
				}));
			}
			
			for(Thread t : threads) {
				t.start();
			}
			
			ctx.close();
			logger.info("done.");
		} catch (NamingException e) {
			throw new RuntimeException(e);
		}
		
	}	
	
}